package com.jsmile.cloud.tradecenter.order.listener;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.jsmile.cloud.tradecenter.api.constants.TradeConstants;
import com.jsmile.cloud.tradecenter.api.res.ResOrder;
import com.jsmile.cloud.tradecenter.api.to.OrderStatusChangeTo;
import com.jsmile.cloud.tradecenter.order.event.OrderCloseEvent;
import com.jsmile.cloud.tradecenter.order.event.OrderCreateEvent;
import com.jsmile.cloud.tradecenter.order.event.OrderPayEvent;
import com.jsmile.cloud.tradecenter.order.event.OrderRefundEvent;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单变化--通知商品中心
 */
@Slf4j
@Component
public class OrderChangeNotifyGoodsListener {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Async
    @Order
    @EventListener(OrderCreateEvent.class)
    public void orderStatusChange(OrderCreateEvent event) {
        log.info("订单创建通知商品扣减库存：{}", event.getOrder());
        sendGoodsMsg(event.getOrder());
    }

    @Async
    @Order
    @EventListener(OrderPayEvent.class)
    public void orderStatusChange(OrderPayEvent event) {
        log.info("订单支付通知商品统计销量：{}", event.getOrder());
        sendGoodsMsg(event.getOrder());
    }

    @Async
    @Order
    @EventListener(OrderCloseEvent.class)
    public void orderStatusChange(OrderCloseEvent event) {
        log.info("订单关闭通知商品扣减销量和回滚库存：{}", event.getOrder());
        sendGoodsMsg(event.getOrder());
    }

    @Async
    @Order
    @EventListener(OrderRefundEvent.class)
    public void orderStatusChange(OrderRefundEvent event) {
        log.info("订单退款通知商品扣减销量和回滚库存：{}", event.getOrder());
        sendGoodsMsg(event.getOrder());
    }

    private void sendGoodsMsg(com.jsmile.cloud.tradecenter.order.model.Order order) {
        ResOrder resOrder = BeanUtil.toBean(order, ResOrder.class);
        resOrder.setOrderNo(order.getId());
        amqpTemplate.convertAndSend(TradeConstants.TradeMq.GOODS_ORDER_STATUS_SYNC_EXCHANGE, TradeConstants.TradeMq.GOODS_ORDER_STATUS_SYNC_ROUTE,
            OrderStatusChangeTo.builder().order(resOrder).orderStatus(order.getOrderStatus()).build());
    }
}
